package logik;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class ChatBean {
	
	private ArrayList<String> chat;
	private ArrayList<String> users;
	
	private File chatfile;
	private File userfile;

	public ChatBean() {
		chat = new ArrayList<>();
		users = new ArrayList<>();
		chatfile = new File("chat.txt");
		userfile = new File("user.txt");
		try {
			chatfile.createNewFile();
			userfile.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void setLogin(String user){
		users.add(user);
	}
	
	public void setLogout(String user){
		users.remove(user);
	}
	
	public String getChatcontent(){
		try{
			chat.clear();
			BufferedReader br = new BufferedReader(new FileReader(chatfile));
			while(br.ready()) chat.add(br.readLine());
			br.close();
		} catch(IOException e){
			e.printStackTrace();
		}
		String temp = "";
		
		chat.add("dummy eintrag 1");
		chat.add("dummy eintrag 2");
		chat.add("dummy eintrag 3");
		
		for(int i=1; i<=30 ; i++){//nur die letzten 30 nachrichten, egal wieviele drin sind
			if(chat.size() - i >= 0) temp += chat.get(chat.size()-i) + "<br>";
		}
		return temp;
	}
	
	public String getUsers(){
		try{
			users.clear();
			BufferedReader br = new BufferedReader(new FileReader(userfile));
			while(br.ready()) users.add(br.readLine());
			br.close();
		} catch(IOException e){
			e.printStackTrace();
		}
		String temp = "";
		
		users.add("dummy user 1");
		users.add("dummy user 2");
		users.add("dummy user 3");
		
		for (String s : users) {
			temp += "<a href='javascript:herausfordern()'>" + s + "</a><br>";
		}
		return temp;
	}
	
	public void setMessage(String message){
		chat.add(message);
		
		PrintWriter pw;
		try {
			pw = new PrintWriter(new FileWriter(chatfile, true));
			pw.println(message);
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
